package com.gateway.web.controller;

import com.gateway.api.config.ApiConfig;
import com.gateway.api.domain.vo.ApiInfo;
import com.gateway.api.domain.web.ReturnInfo;
import com.gateway.api.util.BeanUtil;
import com.gateway.api.util.LoginUtil;
import com.gateway.service.ApiService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @author: shaoyu1
 * @date: 2019/11/12 17:39
 */
@RequestMapping("/apiInfo")
@Controller
public class ApiInfoController extends BaseController{
    @Autowired
    ApiService apiService;

    private String apiView = "api/apiList";

    @RequestMapping("/index")
    public String index(){
        return afterController(apiView);
    }
    @ResponseBody
    @RequestMapping("/list")
    public ReturnInfo<List<ApiInfo>> getList(int page, int limit){
        return ReturnInfo.success(afterController(apiService.getAll()));
    }
    @RequestMapping("/addApi")
    public String addApi(String apiId, ModelMap modelMap) {
        modelMap.put("type",2);
        if(StringUtils.isNotEmpty(apiId)){
            //编辑
            modelMap.put("type",1);
            modelMap.put("apiInfo",apiService.getApiInfoById(apiId));
        }
        return "api/addApi";
    }
    @RequestMapping("/update")
    @ResponseBody
    public ReturnInfo<String> add(ApiInfo apiInfo,HttpServletRequest req){
        if(apiInfo.getId()!=null){
            apiService.update(apiInfo);
        }else{
            apiInfo.setCreateTime(new Date());
            apiInfo.setCreateUser(LoginUtil.getUsername(req));
            apiInfo.setStatus(1);
            apiService.add(apiInfo);
        }
        return ReturnInfo.success("操作成功!");
    }
    @RequestMapping(value = "/updateStatus",method = RequestMethod.POST)
    @ResponseBody
    public ReturnInfo<String> updateStatus(String apiIds,String status){
        apiService.updateStatus(apiIds,status);
        return ReturnInfo.success("操作成功!");
    }
    @RequestMapping(value = "/refresh",method = RequestMethod.POST)
    @ResponseBody
    public ReturnInfo<String> refresh(){
        try{
            ApiConfig apiConfig = BeanUtil.getBean(ApiConfig.class);
            apiConfig.reset();
        }catch (Exception e){
            return ReturnInfo.defaultError();
        }
        return ReturnInfo.success("成功!");
    }
}
